package com.wxh.utils;

import com.alibaba.fastjson.JSONArray;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: HttpUtils
 * @Description:  HttpClient工具类
 * @Author wxh
 * @Date: 2020/7/15 15:19
 * @Version V1.0.0
 * @Since 1.8
 */
public class HttpUtils {

	private HttpUtils(){

	}

	/**
	 * 创建参数
	 * @param paramMap 参数
	 * @return  byte[]
	 * @throws UnsupportedEncodingException 
	 */
	private static byte[] buildParamter(Map<String, String> paramMap, 
		String encoding) throws UnsupportedEncodingException {
		StringBuilder params = new StringBuilder("");
		
		if (paramMap != null && !paramMap.isEmpty()) {
			for (Map.Entry<String, String> entry : paramMap.entrySet()) {
				if (StringUtils.hasText(params)) {
					params.append("&");
				}
				
				String val = URLEncoder.encode(entry.getValue(), encoding);
				params.append(entry.getKey()).append("=").append(val);
			}
		}
		
		return params.toString().getBytes();
	}

	/**
	 * http get请求
	 * @param urlPath URL
	 * @param paramMap 参数
	 * @return String
	 * @throws IOException
	 */
	public static String doGet(String urlPath, Map<String, String> paramMap) 
			throws IOException {
		return doGet(urlPath, paramMap, "UTF-8");
	}

	/**
	 * http get请求
	 * @param urlPath URL
	 * @param paramMap 参数
	 * @param charset 字符编码
	 * @return String
	 * @throws IOException
	 */
	public static String doGet(String urlPath, Map<String, String> paramMap, 
		String charset) throws IOException {
		HttpURLConnection conn = null;
		ByteArrayOutputStream bs = null;
		InputStream is = null;

		byte[] byteArr = new byte[1024];
		try {
			
			if (paramMap != null && !paramMap.isEmpty()) {
				if (urlPath.indexOf('?') == -1) {
					urlPath += "?" + buildParamter(paramMap, charset).toString();
				} else {
					urlPath += "&" + buildParamter(paramMap, charset).toString();
				}
			}
			
			conn = (HttpURLConnection) new URL(urlPath).openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setRequestMethod("GET");
			conn.connect();

			is = conn.getInputStream();
			bs = new ByteArrayOutputStream();
			
			int len = 0;
			while ((len = is.read(byteArr)) != -1) {
				bs.write(byteArr, 0, len);
			}
			
			return new String(bs.toByteArray(), charset);
		} catch (IOException e) {
			throw e;
		} finally {
			if (bs != null) {
				bs.close();
			}
			
			if (is != null) {
				is.close();
			}

			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	/**
	 * HTTP POST请求
	 * @param urlPath URL
	 * @param paramMap 参数
	 * @return String
	 * @throws IOException
	 */
	public static String doPost(String urlPath, Map<String, String> paramMap)
			throws IOException {
		return doPost(urlPath, paramMap, "UTF-8");
	}

	/**
	 * HTTP POST请求
	 * @param urlPath URL
	 * @param paramMap 参数
	 * @param charset 字符编码
	 * @return String
	 * @throws IOException
	 */
	public static String doPost(String urlPath, Map<String, String> paramMap, 
			String charset) throws IOException {
		return doPost(urlPath, "application/x-www-form-urlencoded", 
				buildParamter(paramMap, charset), charset);
	}

	/**
	 * HTTP POST请求
	 * @param path URL
	 * @param contentType 内容类型
	 * @param body 参数内容
	 * @param charset 字符编码
	 * @return String
	 * @throws IOException
	 */
	public static String doPost(String path, String contentType, byte[] body,
			String charset) throws IOException {

		HttpURLConnection conn = null;
		OutputStream os = null;
		ByteArrayOutputStream bs = null;
		InputStream is = null;

		byte[] byteArr = new byte[1024];
		try {
			conn = (HttpURLConnection) new URL(path).openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", contentType);
			conn.connect();

			os = conn.getOutputStream();
			if (os != null) {
				os.write(body);
				os.flush();
			}

			bs = new ByteArrayOutputStream();
			is = conn.getInputStream();
			
			int len = 0;
			while ((len = is.read(byteArr)) != -1) {
				bs.write(byteArr, 0, len);
			}
			
			return new String(bs.toByteArray(), charset);
		} catch (IOException e) {
			throw e;
		} finally {
			if (bs != null) {
				bs.close();
			}
			
			if (is != null) {
				is.close();
			}

			if (os != null) {
				os.close();
			}

			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	/**
	 * HTTP post请求
	 * @param urlPath URL
	 * @param contentType 内容类型
	 * @param body 参数内容
	 * @param charset 字符编码
	 * @return String
	 * @throws IOException
	 */
	public static String doPost(String urlPath, String contentType, String body, 
			String charset) throws IOException {
		return doPost(urlPath, contentType, body.getBytes(charset), charset);
	}
	

	/**
	 *  一种任意对象的简单发送方式，对应接口方法上面加注释responseBody 方法参数加responseBody （springMVC）
	 * @param urlPath URL
	 * @param obj 参数内容
	 * @return String
	 * @throws IOException
	 */
	public static String doPostSimple(String urlPath, Object obj) throws IOException{
		return doPost(urlPath,"application/json",JSONArray.toJSONString(obj),"UTF-8");
	}
	
	
	/**
	 * 默认json格式的utf-8编码
	 * @param urlPath URL
	 * @param body 参数内容
	 * @return String
	 * @throws IOException
	 */
	public static String doPost(String urlPath, String body) throws IOException{
		return doPost(urlPath,"application/json",body,"UTF-8");
	}
	
	public  static void main(String[] args) {
		try {
			String urlPath = "http://192.168.30.64:8888/springmvc/accessToken";
			String userName = "wxh12345";
			String password = "!wxh12345";
			urlPath = urlPath + "?username="+userName+"&password="+password;
			Map<String, String> paramMap = new HashMap<>(16);
			paramMap.put("userId","123456");
			paramMap.put("userId22","123456");
			System.out.println(paramMap);
			String result = HttpUtils.doPostSimple(urlPath,JSONArray.toJSONString(paramMap));
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
